31. Exercise: SmarterSyncing

This Exercise is all about optimizing the synchronization process that was made in the previous exercise. It’s best practice to not initialize things more than once, so for that, we will make sure that startImmediateSync will only get called once when the app starts and only if the database was empty.

** To do so, inside SunshineSyncUtils class: **

  • (1) Create a boolean flag called sInitialized. This will be mainly used as a safeguard to prevent calling the synchronize method more than once.
  • (2) Next create an initialize method that will use that boolean to guarantee that startImmediateSync is called only when necessary!
  • (3) Within it, don’t do any work if the sInitialized flag is already set to true. If it isn’t set to true, we want to check to see if our ContentProvider is empty, in case for example the app was just freshly installed and had no data stored yet!.
  • (4) To check if the ContentProvider is empty, simply run a query and get the result count, but do so on a background thread using an AsyncTask.
  • (5) If the ContentProvider is in fact empty, go ahead and call startImmediateSync.

Exercise: SmarterSyncing

Now it's your turn to optimize the initialization process of our SunshineSyncUtil class. Follow the TODOs in this exercise and check the steps below when you're done.

Exercise Code

Exercise: S10.02-Exercise-SmarterSyncing

SOLUTION:
  • Create a new method in SunshineSyncUtil called initialize
  • Create and use a static boolean that will only be set when initialize is called for the first time
  • Inside initialize, if the boolean was false, start an AsyncTask to query the database
  • If the database was empty, call startImmediateSync and to fill the database with data